from wtforms import IntegerField, StringField, BooleanField
from wtforms.validators import DataRequired, Length, Regexp, ValidationError

from app.common.enums import RegexpEnum, AuthPermissionType
from app.models import AuthPermission
from app.form.base_form import BaseForm


class AuthPermissionForm(BaseForm):
    """权限表单验证
    """
    id = IntegerField('记录ID')
    p_code = StringField(validators=[
        DataRequired('权限标识不允许为空'),
        Length(4, 255, '权限标识长度4~255字符'),
        Regexp(regex=RegexpEnum.words, message='权限标识为字母和数字组合')
    ])
    p_name = StringField(validators=[
        DataRequired('权限名称不允许为空'),
        Length(max=255, message='权限名称最大长度255字符'),
    ])
    p_type = IntegerField("权限类型")
    is_enabled = BooleanField("是否启用")
    description = StringField(validators=[Length(max=255, message='角色名称最大长度255字符')])

    def validate_p_code(self, field):
        """验证权限标识是否已经存在
        """
        # 如果添加，判断权限标识是否已经存在
        # 如果修改，修改到的权限标识不能已经存在
        data = AuthPermission.query.filter_by(p_code=field.data).first()
        id = self.id.data
        if (id is not None) and (data is not None) and (not data.id == id):
            raise ValidationError(message=f"权限标识{field.data}已存在")
        # 没传入id，添加操作，只需要判断是否存在记录
        if (id is None) and (data is not None):
            raise ValidationError(message=f"权限标识{field.data}已存在")

    def validate_p_type(self, field):
        """权限类型验证
        """
        type_dict = AuthPermissionType._value2member_map_
        if int(field.data) not in type_dict:
            raise ValidationError(message="未知的权限类型")
